﻿<?php
session_start();
include_once  "config.php";

//添加商品到会话变量
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
	foreach($_POST as $key => $value){ //提取表单数据
		$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);//$new_product一维关联数组
    }
	//删除表单数据中无关项
	unset($new_product['type']);
	unset($new_product['return_url']); 
	
 	//根据商品码查商品名和价格
    $stmt= $dbh->prepare("SELECT product_name, price FROM products WHERE product_code=? LIMIT 1");
    $stmt->bindParam('1', $new_product['product_code']);
    $stmt->execute();

	
	while(list($product_name, $price) = $stmt->fetch(PDO::FETCH_NUM)){
		
		//$new_product添加商品名和价格
        $new_product["product_name"] = $product_name; 
        $new_product["product_price"] = $price;
        //购物车已经有此商品，数量增1
        if(isset($_SESSION["cart_products"][$new_product['product_code']]))
            $_SESSION["cart_products"][$new_product['product_code']]['product_qty']++;
        else//新选购的商品
        //每一行的键名是商品码，每一行的值是一维数组的值$new_product
        $_SESSION["cart_products"][$new_product['product_code']] = $new_product;

    };
}
//更新数量/退订商品 
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
	//更新数量
	if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){//有值且是数组
		foreach($_POST["product_qty"] as $key => $value){//$key商品码 $value商品数量
			if(is_numeric($value)){
				$_SESSION["cart_products"][$key][] = $value;
			}
		}
	}
	//退订
	if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){//有值且是数组
		foreach($_POST["remove_code"] as $key){//$key表示商品码
			unset($_SESSION["cart_products"][$key]);//删除$key行
		}	
	}
}

//返回index.php
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url

header('Location:'.$return_url);

